<!DOCTYPE html>
<html lang="en">
<head>
    <title>Select Features To Java</title>
    <style>
        .map {
            width: 100%;
            height:100%;
        }
    </style>
    <link href="css/ol.css" type="text/css">
    <script src="js/jquery-1.11.2.min.js" type="text/javascript"></script>
    <script src="js/ol.js" type="text/javascript"></script>

</head>
<body>
<div id="map" class="map"></div>
<button id="SelectFeatureToJava" onclick="SelectFeatureToJava()">选择要素并传送给java后端</button>
<script type="application/javascript">

    //瓦片底图，源为OSM底图
    var raster = new ol.layer.Tile({
        source: new ol.source.OSM(),
    });

    //中国的矢量图层，通过geojson数据和GeoJSON()解析器的方式加载进来
    var vector = new ol.layer.Vector({
        source: new ol.source.Vector({
            url: 'china.json',
            format: new ol.format.GeoJSON(),
        }),
    });

    //初始化map，加到id = "map"的容器中进行显示
    var map = new ol.Map({
        layers: [raster,vector],
        target:'map',
        view:new ol.View({
            center:[0,0],
            zoom:2,
            projection:'EPSG:3857',
        }),
    });

    //使用交互控件中的选择控件ol.interaction.Select
    var select = new ol.interaction.Select({
        //condition:ol.event.condition.pointerMove, 鼠标指针移动时选择要素
        condition: ol.events.condition.SINGLECLICK,  //单击时选择要素
        style:new ol.style.Style({
            fill: new ol.style.Fill({
                color: 'rgba(255,255,255,0.7)',
            }),
            stroke: new ol.style.Stroke({
                color: '#3399CC',
                width: 3,
            }),
        })
    });
    map.addInteraction(select);

    var selected = null;
    function SelectFeatureToJava() {
        //通过select控件的getFeatures()方法获取选中的要素
        selected = select.getFeatures();
        //console.log(selected);

        //省的坐标
        var coord = selected.array_[0].values_.geometry.flatCoordinates;
        //省的名称
        var name = selected.array_[0].values_.name;
        //console.log(coord);
        //console.log(name);

        //省份的名字和坐标组成的js对象
        var nameAndCoord = {
            name:name,
            coord:coord,
        };
        console.log(nameAndCoord);
        //通过ajax向后端发起请求
        $.ajax({
            //请求方式
            type: "post",
            url: "/featureToJava",
            data: JSON.stringify(nameAndCoord),
            contentType: "application/json;charsets=UTF-8",//必须
            dataType: "json",//必须
            success: function (data) { //回调函数，本次没用到
                console.log(data);
            }
        });
    }


</script>
</body>
</html>